<template>
  <div class="page-container network-config">
    <div v-if="loading && !error" class="loading-spinner">
      <el-progress type="circle" :percentage="100" status="success" :indeterminate="true" :duration="2" />
      <p>正在加载网络数据...</p>
    </div>

    <div v-else-if="error" class="error-message">
      <el-alert type="error" :title="'网络数据加载失败'" :description="error" show-icon :closable="false" />
    </div>

    <div v-else class="page-content">
      <el-row :gutter="20">
        <!-- 左侧: 当前网络信息 -->
        <el-col :span="8">
          <el-card shadow="hover" class="info-card">
            <template #header>
              <div class="card-header">
                <el-icon><Connection /></el-icon>
                <span>当前连接</span>
              </div>
            </template>
            <el-descriptions :column="1" border>
              <el-descriptions-item label-class-name="info-label" label="类型">
                <el-tag :type="networkSettings.type === 'wifi' ? 'success' : 'primary'">
                  <el-icon><component :is="networkSettings.type === 'wifi' ? Iphone : Upload" /></el-icon>
                  <span style="vertical-align: middle; margin-left: 5px;">{{ networkSettings.type === 'wifi' ? '无线 WiFi' : '有线' }}</span>
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label-class-name="info-label" label="SSID" v-if="networkSettings.type === 'wifi'">
                {{ networkSettings.wifi_ssid }}
              </el-descriptions-item>
              <el-descriptions-item label-class-name="info-label" label="IP 地址">{{ networkSettings.ip || 'N/A' }}</el-descriptions-item>
              <el-descriptions-item label-class-name="info-label" label="网关">{{ networkSettings.gateway || 'N/A' }}</el-descriptions-item>
              <el-descriptions-item label-class-name="info-label" label="DNS">{{ networkSettings.dns?.join(', ') || 'N/A' }}</el-descriptions-item>
            </el-descriptions>
          </el-card>
        </el-col>

        <!-- 右侧: WiFi管理 -->
        <el-col :span="16">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <div>
                  <el-icon><List /></el-icon>
                  <span>可用 WiFi 网络</span>
                </div>
                <el-button type="primary" @click="scanWifi" :loading="scanning" plain>
                  <el-icon><Refresh /></el-icon>
                  {{ scanning ? '扫描中...' : '重新扫描' }}
                </el-button>
              </div>
            </template>
            
            <el-table :data="wifiNetworks" stripe style="width: 100%" v-loading="scanning" empty-text="扫描中或未发现WiFi网络...">
              <el-table-column prop="ssid" label="网络名称 (SSID)" min-width="180" show-overflow-tooltip />
              <el-table-column label="信号强度" min-width="150">
                <template #default="scope">
                  <div class="signal-strength">
                    <el-progress 
                      :percentage="scope.row.signal" 
                      :stroke-width="8"
                      :color="getSignalColor(scope.row.signal)"
                      :show-text="false"
                    />
                    <span class="signal-text">{{ scope.row.signal }}%</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="security" label="加密方式" width="120" align="center">
                <template #default="scope">
                   <el-tag :type="scope.row.security.includes('WPA') ? 'success' : 'info'" size="small" effect="dark">
                    <el-icon><Lock v-if="scope.row.security !== 'open'"/></el-icon>
                    {{ scope.row.security }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100" align="center">
                <template #default="scope">
                  <el-button 
                    v-if="scope.row.ssid !== networkSettings.wifi_ssid"
                    size="small" 
                    type="primary"
                    @click="handleConnect(scope.row)">
                    连接
                  </el-button>
                  <el-button v-else size="small" type="success" disabled>已连接</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- WiFi连接对话框 -->
      <el-dialog v-model="connectDialog.visible" :title="`连接到网络: ${connectDialog.form.ssid}`" width="400px" destroy-on-close>
        <el-form :model="connectDialog.form" label-position="top" @submit.prevent="confirmConnect">
          <el-form-item label="密码" v-if="connectDialog.form.security !== 'open'">
            <el-input 
              v-model="connectDialog.form.password" 
              type="password" 
              show-password
              placeholder="请输入WiFi密码"
              autofocus
            />
          </el-form-item>
          <el-alert v-else title="这是一个开放网络，连接可能不安全。" type="warning" :closable="false" show-icon />
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="connectDialog.visible = false">取消</el-button>
            <el-button type="primary" @click="confirmConnect" :loading="connecting">
              {{ connecting ? '正在连接...' : '确认连接' }}
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus';
import { Connection, Iphone, Upload, List, Refresh, Lock } from '@element-plus/icons-vue';
import api from '@/services/api';

const loading = ref(true);
const scanning = ref(false);
const connecting = ref(false);
const error = ref(null);

const networkSettings = ref({});
const wifiNetworks = ref([]);

const connectDialog = reactive({
  visible: false,
  form: {
    ssid: '',
    password: '',
    security: ''
  }
});

// 将信号强度（0-100）转换为颜色
const getSignalColor = (percentage) => {
  if (percentage > 75) return '#67C23A';
  if (percentage > 40) return '#E6A23C';
  return '#F56C6C';
};

const fetchNetworkSettings = async () => {
  try {
    const response = await api.getNetworkSettings();
    networkSettings.value = response.data.data;
  } catch (err) {
    error.value = `无法从后端服务获取网络数据。请检查后端服务是否正在运行并且网络API是否可用。错误: ${err.message}`;
    console.error(err);
  } finally {
    loading.value = false;
  }
};

const scanWifi = async () => {
  scanning.value = true;
  try {
    const response = await api.scanWifi();
    // 确保返回的数据是一个数组
    if (response.data && Array.isArray(response.data.networks)) {
        wifiNetworks.value = response.data.networks;
        ElMessage.success(`扫描完成，发现 ${wifiNetworks.value.length} 个网络`);
    } else {
        wifiNetworks.value = [];
        ElMessage.warning('WiFi扫描未返回有效数据。');
    }
  } catch (err) {
    wifiNetworks.value = []; // 扫描出错时清空列表
    ElMessage.error('WiFi扫描失败: ' + (err.response?.data?.error || err.message));
    console.error(err);
  } finally {
    scanning.value = false;
  }
};

const handleConnect = (network) => {
  connectDialog.form.ssid = network.ssid;
  connectDialog.form.security = network.security;
  connectDialog.form.password = '';
  connectDialog.visible = true;
};

const confirmConnect = async () => {
  connecting.value = true;
  const { ssid, password } = connectDialog.form;

  try {
    await api.connectWifi({ ssid, password });
    ElNotification({
      title: '连接请求已发送',
      message: `正在尝试连接到 ${ssid}。请稍后刷新页面查看状态。`,
      type: 'success',
      duration: 5000
    });
    connectDialog.visible = false;
    
    // 10秒后自动刷新数据
    setTimeout(() => {
        fetchNetworkSettings();
        scanWifi();
    }, 10000);
  } catch (err) {
    ElMessage.error(`连接失败: ${err.response?.data?.error || err.message}`);
  } finally {
    connecting.value = false;
  }
};

onMounted(async () => {
  await fetchNetworkSettings();
  // 只有在获取设置成功后才扫描wifi
  if (!error.value) {
    scanWifi();
  }
});
</script>

<style scoped>
.network-config {
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}

.card-header .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.info-card .el-icon {
  vertical-align: middle;
}

.info-label {
  font-weight: 600 !important;
  background-color: #fafafa !important;
}

.signal-strength {
  display: flex;
  align-items: center;
}
.signal-text {
  margin-left: 10px;
  color: #606266;
  font-size: 12px;
  width: 40px;
}
.el-table .el-icon {
    vertical-align: middle;
    margin-right: 4px;
}
</style> 